package com.huluobo.a2109mouthdemo.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by LC on 2023/12/2.
 */
public class MyView extends View {
    private Paint paint;
    private String timeString;
    private int progress;

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
        paint.setTextSize(100);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        RectF rectF = new RectF(100, 100, 600, 600);
        canvas.drawArc(rectF, 270, progress, false, paint);
        canvas.drawText(timeString, 320, 380, paint);
    }

    public void start(int time) {
        ValueAnimator animator = ValueAnimator.ofInt(0, 360);
        animator.addUpdateListener(animation -> {
            progress = (int) animation.getAnimatedValue();
            invalidate();
        });
        animator.setDuration(time * 1000L);
        animator.start();

        ValueAnimator animatorText = ValueAnimator.ofInt(time, 0);
        animatorText.addUpdateListener(animation -> {
            timeString = String.valueOf(animatorText.getAnimatedValue());
            invalidate();
        });
        animatorText.setDuration(time * 1000L);
        animatorText.start();

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                onAnimEndListener.onAnimEnd();
            }
        });
    }

    public interface OnAnimEndListener {
        void onAnimEnd();
    }

    private OnAnimEndListener onAnimEndListener;

    public void setOnAnimEndListener(OnAnimEndListener onAnimEndListener) {
        this.onAnimEndListener = onAnimEndListener;
    }
}
